<template>
  <div class="keyboard_container">
    <!-- 新增左侧信息展示区 -->
    <div class="header_info">
      <h2 class="title">脚本执行界面</h2>
      <div class="file_info">
        <h3>{{ name }}</h3>
        <span>总时长: {{ formatTime(maxTime) }}</span>
      </div>
    </div>
    <el-divider />
    <div class="script_operations" ref="scrollContainerRef">
      <el-timeline class="script_operations_content">
        <el-timeline-item
          v-for="(message, index) in operations"
          :key="index"
          :timestamp="formatTime(message.timestamp)"
          :color="getItemColor(index)"
          :ref="
            (el) => {
              if (el) timelineItems[index] = el
            }
          "
        >
          {{ getMessage(message) }}
        </el-timeline-item>
      </el-timeline>
    </div>

    <el-divider />
    <div class="action_container">
      <div class="script_info">
        <span class="info-item progress-container">
          <span>当前进度:</span>
          <el-progress
            :percentage="progress"
            :status="progressStatus"
            :stroke-width="18"
            :text-inside="true"
            style="width: 300px"
          />
        </span>
        <span class="info-item">剩余操作: {{ remainingOperations }}</span>
      </div>
      <div class="actions">
        <el-button
          class="action_button"
          :type="isRunnig ? 'danger' : 'primary'"
          :icon="isRunnig ? VideoPause : VideoPlay"
          @click="toggleScript"
        >
          {{ isRunnig ? '停止执行脚本' : '开始执行脚本' }}({{ hotkeyLabel }})
        </el-button>
        <el-button
          @keydown.space.prevent
          @keydown.enter.prevent
          class="action_button"
          type="success"
          :icon="Refresh"
          @click="resetScript"
          :disabled="isRunnig"
        >
          重置脚本
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { inject, ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { VideoPlay, VideoPause, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import request from '@/utils/request.js'

const route = useRoute()
const router = useRouter()

const path = ref('')

const operations = ref([])
const name = ref('')
const maxTime = ref(0)

const isRunnig = ref(false) // 执行器是否在运行
const index = ref(0) // 记录执行到的操作index

const timelineRef = ref(null)
const timelineItems = ref([])
const currentIndex = ref(-1)
// 新增滚动容器ref
const scrollContainerRef = ref(null)

//进度条状态变量
const progress = ref(0)
const progressStatus = ref('warning')

// 计算属性
const remainingOperations = computed(() => `${operations.value.length - currentIndex.value - 1}项`)

const hotkeyLabel = ref('F9')

onMounted(async () => {
  const res = await request.get('/setting/name/script.run.toggle')
  hotkeyLabel.value = res.data.key
})

const getItemColor = (index) => {
  if (index < currentIndex.value) return '#67C23A' // 已完成-绿色
  // if (index === currentIndex.value) return '#67C23A' // 当前项-绿色
  return '#909399' // 未执行-灰色
}

const updateProgress = () => {
  progress.value = Number(((currentIndex.value / operations.value.length) * 100).toFixed(1))
  progressStatus.value = isRunnig.value ? 'success' : 'warning'
  console.log('进度条值：', progress.value, '进度条状态：', progressStatus.value)
}
// 自动滚动逻辑
const scrollToCurrent = () => {
  nextTick(() => {
    const container = scrollContainerRef.value // 获取正确的滚动容器
    const activeItem = timelineItems.value[currentIndex.value]?.$el

    if (container && activeItem) {
      // 使用更精准的位置计算
      const itemRect = activeItem.getBoundingClientRect()
      const containerRect = container.getBoundingClientRect()
      const scrollTop =
        itemRect.top - containerRect.top + container.scrollTop - container.clientHeight / 2

      container.scrollTo({
        top: scrollTop,
        behavior: 'smooth',
      })
    }
  })
}

// 手动实现节流函数
const throttle = (func, delay) => {
  let lastCall = 0
  return function (...args) {
    const now = new Date().getTime()
    if (now - lastCall < delay) {
      return
    }
    lastCall = now
    return func.apply(this, args)
  }
}

// 使用节流包装 scrollToCurrent 函数，例如每 500 毫秒最多执行一次
const throttledScrollToCurrent = throttle(scrollToCurrent, 500)

const toggleScript = async () => {
  request.post('/script/run/toggle')
}
const resetScript = async () => {
  request.post('/script/run/reset')
}
const formatTime = (millis) => {
  // 将输入值转为数值型（防御性处理）
  const ms = Math.abs(Number(millis) || 0)
  // 分解时间单位
  const hours = Math.floor(ms / 3600000)
  const minutes = Math.floor((ms % 3600000) / 60000)
  const seconds = Math.floor((ms % 60000) / 1000)
  const remainingMs = ms % 1000
  // 格式化各部分（补零处理）
  const pad = (n, length) => String(n).padStart(length, '0')
  return [
    pad(hours, 2), // 小时两位数
    pad(minutes, 2), // 分钟两位数
    pad(seconds, 2), // 秒两位数
    pad(remainingMs, 3), // 毫秒三位数
  ].join(':')
}
const getMessage = (operation) => {
  if (operation.type == 'mm') return `鼠标移动至【${operation.x}, ${operation.y}】`
  else if (operation.type == 'mp') return `鼠标按下按键${operation.button}`
  else if (operation.type == 'mr') return `鼠标释放按键${operation.button}`
  else if (operation.type == 'wc') return `鼠标滚动${operation.units}单位`
  else if (operation.type == 'kp') return `键盘按下按键${operation.keyCode}`
  else if (operation.type == 'kr') return `键盘释放按键${operation.keyCode}`
  else return '未知按键'
}

const getOperations = async () => {
  const res = await request.post('/script/run/list')
  if (res.code == 0) {
    name.value = res.data.name
    maxTime.value = res.data.time
    operations.value = res.data.list
    console.log(operations)
  } else {
    setTimeout(getOperations, 5000)
  }
}

onMounted(() => {
  path.value = route.params.path || ''
  // 如果参数不存在（直接访问或刷新）
  if (!path.value) {
    router.replace('/scriptManagement') // 跳转回脚本管理页面
    return
  }
  console.log('获取的路径:', path.value)
})

const webSocketManager = inject('webSocketManager') // 通过inject获取全局实例
// WebSocket订阅回调
const handleScriptRunMessage = (status) => {
  // 执行监听操作
  isRunnig.value = status.state == 'RUNNING' || status.state == 'COUNTDOWN'
  currentIndex.value = status.currentIndex
  if (status.state == 'COUNTDOWN') {
    // 当处于倒计时状态时，显示所有消息
    for (var i of status.messages) {
      ElMessage.success(i.message)
    }
  }
  throttledScrollToCurrent() // 调用节流后的滚动函数
  updateProgress() // 更新进度条
}
onMounted(async () => {
  // 订阅WebSocket频道
  webSocketManager.subscribe('/topic/script-run-message', handleScriptRunMessage)
  // 调用绑定接口（假设需要）
  await request.post('/script/run/bind', {
    path: route.params.path || '',
  })
  getOperations()
})

// 页面卸载时：取消订阅+解绑接口
onUnmounted(async () => {
  // 取消WebSocket订阅
  webSocketManager.unsubscribe('/topic/script-run-message')
  await request.post('/script/run/unbind')
})
</script>

<style lang="less" scoped>
@import url('../assets/main.less');

.keyboard_container {
  padding: 0px 24px;
  border-radius: 12px;

  .header_info {
    display: flex;
    justify-content: space-between;

    .title {
      color: var(--el-text-color-primary);
      font-size: 1.5em;
      margin-bottom: 1em;
      position: relative;
      margin-top: 10px;

      &::after {
        content: '';
        position: absolute;
        bottom: -8px;
        left: 0;
        width: 50px;
        height: 3px;
        background: @primary-color;
      }
    }
  }

  .script_operations {
    width: 96%;
    margin: auto;
    height: calc(100vh - 320px);
    overflow-y: auto;
    border: 1px solid black;
    border-radius: 8px;
    padding: 8px;
  }

  .action_container {
    display: flex;
    justify-content: space-between;

    .script_info {
      display: flex;
      gap: 10px;

      span {
        line-height: 32px;
      }

      .progress-container {
        display: flex;
        gap: 8px;
      }
    }
  }
}
</style>
